package com.kaishengit.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.kaishengit.entity.Task;
import com.kaishengit.util.db.DBHelp;
import com.kaishengit.util.db.RowMapper;

public class TaskDao {
	private DBHelp<Task> db = new DBHelp<Task>();
	
	public void save(Task task){
		String sql="insert into t_task (id,name,createtime,description,state,level,starttime,endtime,userId,goalId) values(?,?,?,?,?,?,?,?,?,?)";
		db.executeSQL(sql, task.getId(),task.getName(),task.getCreateTime(),task.getDescription(),task.getState(),task.getLevel(),task.getStartTime(),task.getEndTime(),task.getUserId(),task.getGoalId());
	}
	
	public void update(Task task){
		String sql="update t_task set name=?,createtime=?,description=?,state=?,level=?,starttime=?,endtime=?,userId=?,goalId=?where id=?";
		db.executeSQL(sql, task.getName(),task.getCreateTime(),task.getDescription(),task.getState(),task.getLevel(),task.getStartTime(),task.getEndTime(),task.getUserId(),task.getGoalId(),task.getId());
	}
	
	public List<Task> findAllTaskByGoalId(int goalId){
		String sql="select id,name,createtime,description,state,level,starttime,endtime,userId,goalId from t_task where goalId=?";
		return db.executeQueryToList(sql, new TaskRowMapper(), goalId);
	}

	private class TaskRowMapper implements RowMapper<Task>{
		public Task mapRow(ResultSet rs) throws SQLException {
			Task task = new Task();
			
			task.setId(rs.getInt("id"));
			task.setName(rs.getString("name"));
			task.setCreateTime(rs.getString("createtime"));
			task.setDescription(rs.getString("description"));
			task.setState(rs.getInt("state"));
			task.setLevel(rs.getString("level"));
			task.setStartTime(rs.getString("starttime"));
			task.setEndTime(rs.getString("endtime"));
			task.setUserId(rs.getInt("userId"));
			task.setGoalId(rs.getInt("goalId"));
			
			return task;
		}
	}

}
